<template>
  <view  @longpress="handleLongPress">
    <view>
      <u-sticky v-show="paramButShow">
        <u-button type="primary" @click="modalData.show = true">查看参数</u-button>
      </u-sticky>
    </view>
    <view>
      <!-- 查询参数弹窗 --->
      <u-modal :show="modalData.show" :content='modalData.content' showCancelButton :showConfirmButton="submitFlag"
               @confirm="handleConfirm" @cancel="modalData.show = false">
        <u-form :model="param" ref="uParam">
          <u-form-item label="订单">
            <view style="display: flex; flex-wrap: wrap;">
              <view class="u-page__tag-item" v-for="(item, index) in param.orderNos" :key="index">
                <u-tag
                    :text="item"
                    size="mini"
                    closable
                    @close="closeItem(item)"
                />
              </view>
            </view>
          </u-form-item>
          <u-form-item label="物料编码">
            <u--input
                placeholder="请输入物料编码"
                border="surround"
                clearable
                v-model="param.invCode"
            ></u--input>
          </u-form-item>
          <u-button type="primary" @click="handleShowParam">选择订单</u-button>
        </u-form>
      </u-modal>
    </view>
    <view>
      <!-- 批量确认弹窗 --->
      <u-modal :show="form.show" :content='form.content' showCancelButton :showConfirmButton="submitFlag" @cancel="form.show = false"
               @confirm="handleSubmit">
        <u-form :model="form" ref="uForm">
          <u-form-item label="物料编码">
            <u--input
                placeholder="请输入物料编码"
                border="surround"
                :disabled="true"
                v-model="form.invCode"
            ></u--input>
          </u-form-item>
          <u-form-item label="订单">
            <view style="display: flex; flex-wrap: wrap;">
              <view class="u-page__tag-item" v-for="(item, index) in form.items" :key="index" style="margin-bottom: 1px;">
                <u-tag
                    :text="parseText(item)"
                    closable
                    @close="clickItem(item)"
                />
              </view>
            </view>
          </u-form-item>
          <u-row>
            <u-col span="6">
              <u--input
                  placeholder="请输入单据总数"
                  border="surround"
                  type="number"
                  :disabled="true"
                  size="small"
                  v-model="form.totalQty"
              ></u--input>
            </u-col>
            <u-col span="6">
                <u--input
                    placeholder="请输入二级帐"
                    border="surround"
                    type="number"
                    :disabled="true"
                    v-model="form.overQty"
                ></u--input>
            </u-col>
          </u-row>
          <u-form-item label="实发数量">
            <u--input
                :placeholder="form.gdQty"
                border="surround"
                clearable
                type="number"
                v-model="form.actQty"
            ></u--input>
          </u-form-item>
        </u-form>
      </u-modal>
    </view>
    <view>
      <!-- 批量确认数据 --->
      <u-list @scrolltolower="scrolltolower" :pagingEnabled="true" :showScrollbar="true" @scrollWithAnimation="true" :key="listKey">
        <u-list-item v-for="(item) in items"  :class="['custom-list-item',`status-${item.batchStatus}`]">
          <u-row>
            <u-col>
              <u-cell :title="`物料编码：${item.invCode}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <view style="display: flex; flex-wrap: wrap;">
              <view class="u-page__tag-item" v-for="(item, index) in item.items" :key="index" style="margin-bottom: 1px;margin-right: 1px">
                <u-tag
                    :text="parseText(item)"
                />
              </view>
            </view>
          </u-row>
          <u-row>
            <u-col>
              <u-cell :title="`单据总数：${item.totalQty}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-cell :title="`二级帐：${item.overQty}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-cell :title="`实发数量：${item.actQty}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-cell :title="`核实人员：${item.verifiedWh}-----${showStr(item.verifiedLine)}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-cell :title="`状态：${getDictValue('over_form_status', item.batchStatus)}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="4" v-show="item.batchStatus === 0 || item.batchStatus === 3">
              <u-button type="warning" @click="handleUpdate(item)">修改</u-button>
            </u-col>
            <u-col span="4">
              <u-button type="primary" @click="handleBatchConfirm(item)">确认</u-button>
            </u-col>
            <u-col span="4" v-show="item.batchStatus === 0 || item.batchStatus === 3">
              <u-button type="warning" @click="handleDel(item)">删除</u-button>
            </u-col>
            <u-col span="8" v-show="item.batchStatus === 1">
              <u-button type="warning" @click="handleRefuse(item)">否决</u-button>
            </u-col>
          </u-row>
        </u-list-item>
      </u-list>
    </view>
    <view>
      <u-picker :show="showOrder" @confirm="confirmOrder" :columns="orders" @cancel="showOrder = false"></u-picker>
    </view>
  </view>
</template>
<script>
import {dealBarCde, destroyScan, initScan} from "@/utils/scanUtil";
import {
  addBatchForm, batchConfirm,
  batchDel,
  batchIssueList,
  batchRefuse,
  getBatchList,
  getOrders, upBatchForm,
} from "@/api/work/stockTrace/bookKeep";
import storage from "@/utils/storage";
import {isEmpty, showStr} from "@/utils/paramUtil";
import {getDictValue, initDict} from "@/utils/dictUtil";

export default {
  data() {
    return {
      paramButShow: false,
      handlePdaScan: null,
      initScanFlag: null,
      param: {
        orderNos:  [],
        invCode: null,
        pageNum: 0,
        pageSize: 10,
      },
      modalData: {
        show: false,
        content: '请输入物料编码',
      },
      form: {
        content: '多订单物料二级帐核对',
        show: false,
        items: [],
        overQty: null,
        gdQty: null,
        actQty: null,
      },
      showOrder: false,
      orders: [],
      listKey: Date.now(),
      total: 0,
      items: [],
      submitFlag: true,
      batchParam: {
        pageNum: 0,
        pageSize: 10,
      }
    }
  },
  beforeDestroy() {
    if (this.initScanFlag) {
      destroyScan(this.handlePdaScan);
    }
  },
  created() {
    initDict(['over_form_status'])
    let that = this;
    this.handlePdaScan = function (res) {
      let barCode = dealBarCde(res);
      if (barCode != null && barCode.invCode != null) {
        that.param.invCode = barCode.invCode;
        if (that.param.orderNos.length === 0) {
          that.modalData.show = true;
          that.$modal.msg("请选择订单！");
        } else {
          that.modalData.show = false;
          that.handleConfirm();
        }
      }
    };
    this.initScanFlag = initScan(this.handlePdaScan);
  },
  onShow() {
    let orders1 = [];
    this.orders = [orders1];
    getOrders().then(res => {
      if (res.data.length > 0) {
        res.data.forEach(item => orders1.push(item));
      }
    });
    let orderNos = storage.getValue("batchIssue.orderNos");
    if (!isEmpty(orderNos) && orderNos !== "") {
      this.param.orderNos = orderNos;
    }
    if (this.items.length === 0) {
      this.paramButShow = true;
    }
    this.refreshData();
  },
  methods: {
    showStr,
    getDictValue,
    handleLongPress() {
      this.paramButShow = true;
      setTimeout(() => {
        this.paramButShow = false;
      }, 5000);
    },
    handleConfirm() {
      // 参数查询提交，生成多订单核对数据
      this.modalData.show = false;
      this.form.totalQty = 0;
      this.submitFlag = false;
      batchIssueList(this.param).then(res => {
        this.submitFlag = true;
        this.form.items = [];
        this.form.iid = null;
        if (res.rows.length > 0) {
          this.form.overQty = parseFloat(res.rows[0].verifiedQty);
          res.rows.forEach(item => {
            this.form.totalQty += parseFloat(item.qty);
            this.form.items.push(item)
          });
          this.form.show = true;
          this.form.invCode = this.param.invCode;
          this.form.actQty = null;
          this.form.gdQty = String(this.form.totalQty - this.form.overQty);
          return;
        }
        this.form.overQty = 0;
        this.$modal.msg("未查询到有效数据！");
        this.form.show = false;
      });
    },
    parseText(item) {
      return '订单：' + item.orderNo + '\r\n数量：' + item.qty;
    },
    handleSubmit() {
      this.submitFlag = false;
      // 提交多订单核对数据持久化，并给与产线确认
      if (isEmpty(this.form.actQty)) {
        this.submitFlag = true;
        this.$modal.msg("请输入实发数量！");
        return;
      }
      if (this.form.items.length === 0) {
        this.submitFlag = true;
        this.$modal.msg("订单信息不能为空！");
        return;
      }
      if (this.form.iid !== null) {
        upBatchForm(this.form).then(() => {
          this.$modal.msgSuccess("修改成功");
          this.form.show = false;
          this.submitFlag = true;
          this.refreshData();
        });
      } else {
        addBatchForm(this.form).then(() => {
          this.$modal.msgSuccess("提交成功");
          this.form.show = false;
          this.submitFlag = true;
          this.refreshData();
        });
      }
    },
    confirmOrder(e) {
      let orderNo = e.value[0];
      if (this.param.orderNos.indexOf(orderNo) !== -1) {
        this.$modal.msg("已添加！");
        return;
      }
      this.showOrder = false;
      this.param.orderNos.push(orderNo);
      storage.put("batchIssue.orderNos", this.param.orderNos);
    },
    handleShowOrder() {
      this.showOrder = true;
    },
    handleShowParam() {
      this.showOrder = true;
    },
    closeItem(item) {
      this.param.orderNos.splice(this.param.orderNos.indexOf(item), 1);
    },
    clickItem(item) {
      this.form.items.splice(this.form.items.indexOf(item), 1);
      this.form.totalQty = 0;
      this.form.items.forEach(obj => {
        this.form.totalQty += parseFloat(obj.qty);
      })
      this.form.gdQty = String(this.form.totalQty - this.form.overQty);
    },
    refreshData() {
      this.batchParam.pageNum = 0;
      this.items = [];
      this.loadMore();
    },
    loadMore() {
      this.batchParam.pageNum += 1;
      getBatchList(this.batchParam).then(res => {
        this.listKey = Date.now();
        if (res.rows.length > 0) {
          res.rows.forEach(item => {
            item.items = JSON.parse(item.itemJonArray);
            this.items.push(item)
          });
        } else {
          this.$modal.msg("无更多数据！");
        }
        this.paramButShow = this.items.length === 0;
      });
    },
    scrolltolower() {
      if (this.items.length >= this.total) {
        this.$modal.showToast("没有更多数据了");
        return;
      }
      // 计算最大页数
      let maxPage = Math.ceil(this.total / this.batchParam.pageSize);
      if (maxPage === this.batchParam.pageNum) {
        this.$modal.showToast("已到最后一页");
        return;
      }
      this.loadMore()
    },
    handleBatchConfirm(item) {
      if (isEmpty(item.actQty)) {
        this.$modal.showToast("实发数量不能为空！！！");
        return;
      }
      batchConfirm(item).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.refreshData();
      });
    },
    handleUpdate(item) {
      this.form.iid = item.iid;
      this.form.show = true;
      this.form.overQty = item.overQty;
      this.form.items = item.items;
      this.form.invCode = item.invCode;
      this.form.actQty = item.actQty;
      this.form.totalQty = item.totalQty;
      this.form.gdQty = String(this.form.totalQty - this.form.overQty);
    },
    handleDel(item) {
      batchDel(item).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.refreshData();
      });
    },
    handleRefuse(item) {
      batchRefuse(item).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.refreshData();
      });
    }
  }
}
</script>
<style>
.custom-list-item {
  /* 如果需要让整个列表项点击区域都生效，可能还需要下面这行 */
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  height: 100%; /* 根据实际情况调整高度 */
}

.status-0 {
  background-color: #ADD8E6;
}

.status-1 {
  background-color: #43dee3;
}

.status-3 {
  background-color: #CCCCCC;
}
</style>
